package com.hmall.common.interceptors;

import cn.hutool.core.util.StrUtil;
import com.hmall.common.utils.UserContext;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 后端所有微服务公共拦截器，获取用户信息（在common模块下，由其它微服务模块引入）
 * 拦截从网关传入的请求
 */

public class UserInfoInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取用户信息
        String userId = request.getHeader("user-info");
        //2.判断是否有用户信息，如果有，则存入ThreadLocal
        if (StrUtil.isNotBlank(userId)){//判断是否为null和空字符串
            UserContext.setUser(Long.valueOf(userId));
        }
        //3.放行:不管怎么样都要放行，因为校验功能在网关已经完成
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //在业务完成后,清理用户
        UserContext.removeUser();
    }
}
